<?php

namespace App\Admin\Actions\OrderAction;

use App\Models\Order;
use App\Models\Reward;
use App\Services\CancelProductOrder\CancelProductOrder;
use Encore\Admin\Actions\RowAction;

class OrderCancel extends RowAction
{
    public $name = '取消';
    
    public function handle(Order $model)
    {
	    if ($model->isClosed()) {
		    return $this->response()->error('目标订单已关闭');
	    } elseif (!$model->isPaid()) {
		    return $this->response()->error('目标订单未支付');
	    } elseif ($model->cancelled_at) {
		    return $this->response()->error('目标订单已取消');
	    }/* elseif ($model->refunds()->first() && $model->refunds()->first()->refund_status !="applied") {
		    return $this->response()->error('目标订单已售后');
	    }*/
    	$reward =Reward::query()->where('order_id',$model->id)->first();
    	if(!empty($reward) && $reward->is_settle){

    		 return $this->response()->error('该订单已结算佣金，不可退回');
    	}

	    app(CancelProductOrder::class, [
	    	'order' => $model
	    ])->cancel();
	    
	    return $this->response()->success('订单取消已提交')->refresh();
    }
	
	public function dialog()
	{
		$this->confirm('确定取消当前订单，谨慎操作?');
	}
}
